const express = require("express");
const FocusModel = require("../model/FocusModel")
const NavModel = require("../model/NavModel")
const ArticleModel = require("../model/ArticleModel")
const ArticleCateModel = require("../model/ArticleCateModel")
const SettingModel = require("../model/SettingModel")


const { formatTime, unixToDay, unixToYearAndMonth } = require("../model/tools")
const mongoose = require("../model/core")
const url = require("url");
const { log } = require("console");

var router = express.Router()

// 公共导航中间件
router.use(async (req, res, next) => {
   let pathname = url.parse(req.url).pathname   // 获取公共数据

   let navResult = await NavModel.find({ "position": 2 }).sort({ "sort": -1 })

   // 绑定全局变量
   req.app.locals.navList = navResult

   req.app.locals.pathname = pathname

   req.app.locals.formatTime = formatTime

   req.app.locals.unixToDay = unixToDay

   req.app.locals.unixToYearAndMonth = unixToYearAndMonth

   req.app.locals.title = "2020北京车展";
   req.app.locals.keywords = "2020北京车展";
   req.app.locals.description = "2022（第十六届）北京国际汽车展览会（Auto China 2022）将在北京中国国际展览中心新馆和中国国际展览中心老馆举行。";

   next()
})

router.get("/", async (req, res) => {
   // 1、轮播图
   let focusResult = await FocusModel.find({ "type": 1 }).sort({ "sort": -1 })

   // 2、展会新闻
   let topNewsList = await ArticleModel.find({ "cid": mongoose.Types.ObjectId("5f718f951dc45e2698739df3") }, "title").limit(4).sort({ "sort": -1 })

   // 3、推荐新闻
   let bestNewsList = await ArticleModel.find({ "is_best": 1 }).limit(4).sort({ "sort": -1 })

   // 4、获取系统设置
   let settingResult = await SettingModel.find({})

   res.render("default/index.html", {
      focusList: focusResult,
      topNewsList,
      bestNewsList,
      title: settingResult[0].site_title,
      keywords: settingResult[0].site_keywords,
      description: settingResult[0].site_description
   })
})

router.get("/overview.html", (req, res) => {
   res.render("default/overview.html", {
      title: "2020北京车展-展会概况",
      keywords: "2020北京车展，北京车展概况",
      description: "2022（第十六届）北京国际汽车展览会（Auto China 2022）将在北京中国国际展览中心新馆和中国国际展览中心老馆举行。"
   })
})

router.get("/news.html", async (req, res) => {

   let page = req.query.page || 1  // 查询第几页的数据
   let cid = req.query.cid || ""
   let pageSize = 5                // 一页显示几条数据

   let json = {}                       // mongo查询条件

   if (cid) {
      json = Object.assign(json, {
         "cid": mongoose.Types.ObjectId(cid)
      })
   } else {
      // 单独获取新闻中心的子分类  
      // let cateResult = await ArticleCateModel.find({ "pid": mongoose.Types.ObjectId('5f5702245aeb0720f8201df9') })
      let cateResult = await ArticleCateModel.find({})

      // 获取子分类下所有的新闻数据
      let tempArr = []

      cateResult.forEach(value => {
         tempArr.push(value._id)
      })

      json = Object.assign(json, {
         "cid": { $in: tempArr }
      })
   }

   let result = await ArticleModel.aggregate([
      {
         $lookup: {
            from: "article_cate",
            localField: "cid",
            foreignField: "_id",
            as: "cate"
         }
      }, {
         $match: json
      }, {
         $sort: { "add_time": -1 }
      }, {
         $skip: (page - 1) * pageSize
      }, {
         $limit: pageSize
      }

   ])

   let count = await ArticleModel.count(json)


   res.render("default/news.html", {
      newsList: result,
      totalPages: Math.ceil(count / pageSize),
      page: page,
      cid
   })

})

router.get("/services.html", async (req, res) => {

   // 一次过遍历所有数据，适用于html页面结构差不多的
   // let result = await ArticleCateModel.aggregate([
   //    {
   //       $lookup: {
   //          from: 'article',
   //          localField: '_id',
   //          foreignField: 'cid',
   //          as: 'articleList'
   //       }
   //    },
   //    {
   //       $match: { "pid": mongoose.Types.ObjectId('5f5702245aeb0720f8201df9') }
   //    },
   //    {
   //       $sort: { "sort": -1 }
   //    }
   // ])
   // console.log(result);

   // 资料下再
   let list1 = await ArticleModel.find({ "cid": mongoose.Types.ObjectId("5f5633dcc0848423a8344dce") })
   // 票务信息
   let list2 = await ArticleModel.find({ "cid": mongoose.Types.ObjectId("5f57022b5aeb0720f8201dfa") })
   // 交通信息
   let list3 = await ArticleModel.find({ "cid": mongoose.Types.ObjectId("5f71965a1dc45e2698739df6") })
   // 平面图
   let list4 = await ArticleModel.find({ "cid": mongoose.Types.ObjectId("5f71964c1dc45e2698739df5") })
   // 同期活动
   let list5 = await ArticleModel.find({ "cid": mongoose.Types.ObjectId("5f8e48fadcfe8721ecea0450") })
   // 周边服务
   let list6 = await ArticleModel.find({ "cid": mongoose.Types.ObjectId("5f7196621dc45e2698739df7") })

   res.render("default/services.html", {
      list1,
      list2,
      list3,
      list4,
      list5,
      list6
   })
})

router.get("/contact.html", (req, res) => {
   res.render("default/contact.html")
})

router.get("/content_:id.html", async (req, res) => {

   let id = req.params.id

   let result = await ArticleModel.find({ "_id": id })

   res.render("default/news_content.html", {
      list: result[0],
      title: result[0].title,
      keywords: result[0].keywords,
      description: result[0].description
   })
})

module.exports = router